<template>
  <div class="app-container">
     <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
       <el-form-item label="申请时间" prop="loaTime">
         <el-date-picker clearable size="small"
           v-model="startTime"
           type="date"
           value-format="yyyy-MM-dd"
           placeholder="选择开始时间">
         </el-date-picker>
		 至
		 <el-date-picker clearable size="small"
		   v-model="endTime"
		   type="date"
		   value-format="yyyy-MM-dd"
		   placeholder="选择结束时间">
		 </el-date-picker>
       </el-form-item>

       <el-form-item>
         <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
         <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
       </el-form-item>
     </el-form>

	<!-- 贷款申请统计图表 -->
	<h3>贷款申请统计</h3>
	<div id="myChart" :style="{width: '100%', height: '500px'}"></div>
  </div>
</template>

<script>
import {
  listLoans
} from "@/api/system/loanschart";

export default{
  name: 'LoansChart',
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      // 贷款表格数据
      loansList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 1000, // 获取足够多的数据用于图表展示
      },
      //开始时间
      startTime:"",
      //结束时间
      endTime:"",
      // x轴数据（日期）
      xData:[],
      // y轴数据（金额）
      yData:[]
    };
  },
  created(){
    this.getList();
  },
  methods:{
    /** 查询贷款列表 */
    getList() {
      this.loading = true;
      listLoans(this.queryParams).then(response => {
        this.loansList = response.rows || [];
        this.processData();
        this.drawChart();
      }).finally(() => {
        this.loading = false;
      });
    },
    
    /** 处理数据 */
    processData() {
      // 清空之前的数据
      this.xData = [];
      this.yData = [];
      
      // 时间筛选
      let filteredData = this.loansList;
      if (this.startTime && this.endTime) {
        const startTime = new Date(this.startTime);
        const endTime = new Date(this.endTime);
        filteredData = this.loansList.filter(item => {
          const itemTime = new Date(item.loaTime);
          return itemTime >= startTime && itemTime <= endTime;
        });
      }
      
      // 按日期分组并计算总金额
      const dateMap = new Map();
      filteredData.forEach(item => {
        if (item.loaTime && item.loaMoney) {
          // 提取日期部分（YYYY-MM-DD）
          const date = item.loaTime.substring(0, 10);
          if (dateMap.has(date)) {
            dateMap.set(date, dateMap.get(date) + item.loaMoney);
          } else {
            dateMap.set(date, item.loaMoney);
          }
        }
      });
      
      // 转换为数组并排序
      const dataArray = Array.from(dateMap, ([date, money]) => ({date, money}));
      dataArray.sort((a, b) => new Date(a.date) - new Date(b.date));
      
      // 分别存入xData和yData
      this.xData = dataArray.map(item => item.date);
      this.yData = dataArray.map(item => item.money);
    },
    
    /** 绘制图表 */
    drawChart(){
      // 确保DOM已更新
      this.$nextTick(() => {
        const chartDom = document.getElementById('myChart');
        if (!chartDom) return;
        
        const myChart = this.$echarts.init(chartDom);
        
        // 图表配置
        const option = {
          title: {
            text: '贷款申请统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: (params) => {
              const date = params[0].name;
              const money = params[0].value;
              return `${date}<br/>贷款金额: ${money.toLocaleString()} 元`;
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: this.xData,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '单位（元）',
            axisLabel: {
              formatter: (value) => {
                if (value >= 10000) {
                  return (value / 10000) + '万';
                }
                return value;
              }
            }
          },
          series: [
            {
              name: '贷款申请金额',
              type: 'bar',
              data: this.yData,
              barMaxWidth: '60',
              itemStyle: {
                color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#83bff6' },
                  { offset: 0.5, color: '#188df0' },
                  { offset: 1, color: '#188df0' }
                ])
              },
              emphasis: {
                itemStyle: {
                  color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#2378f7' },
                    { offset: 0.7, color: '#2378f7' },
                    { offset: 1, color: '#83bff6' }
                  ])
                }
              }
            }
          ]
        };
        
        // 设置图表配置
        myChart.setOption(option);
        
        // 窗口大小改变时重置图表大小
        window.addEventListener('resize', () => {
          myChart.resize();
        });
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.startTime = "";
      this.endTime = "";
      this.getList();
    }
  }
}
</script>

<style scoped>
.app-container {
  background: #fff;
  padding: 20px;
}
</style>
